﻿using UnityEngine;
using System.Collections;

namespace Hont.BlazingNodePackage
{
    public class BlazingNodeMono : MonoBehaviour
    {
        public string resourcePath;
        public bool debugMode;
        BlazingNode mBlazingNode;
        object mContext;

        public BlazingNode BlazingNode
        {
            get
            {
                if (mBlazingNode == null) mBlazingNode = new BlazingNode();

                return mBlazingNode;
            }
        }


        protected virtual void OnEnable()
        {
            BlazingNode.Load(resourcePath);

            if (mContext == null)
                mContext = InitDefaultContext();

            BlazingNode.Start(this, mContext, debugMode);
        }

        protected virtual void OnDisable()
        {
            BlazingNode.Teminate(this);
        }

        protected virtual void OnDestroy()
        {
            BlazingNode.Teminate(this);
        }

        public void InitContext(object context)
        {
            mContext = context;
        }

        public void ResetBlazingNode()
        {
            mBlazingNode = null;
        }

        [ContextMenu("Selection Script")]
        void SelectionScript()
        {
#if UNITY_EDITOR
            UnityEditor.Selection.activeObject = UnityEditor.MonoScript.FromMonoBehaviour(this);
#endif
        }

        protected virtual object InitDefaultContext()
        {
            object result = null;

            var animator = GetComponent<Animator>();
            if (animator != null)
            {
                result = new StandardCharacterContext() { GameObject = gameObject, MonoBehaviour = this, Animator = animator };
            }
            else
            {
                result = new StandardContext() { GameObject = gameObject, MonoBehaviour = this };
            }

            return result;
        }
    }
}
